// ignore_for_file: use_build_context_synchronously, deprecated_member_use

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../project_provider.dart';
import '../project.dart';
import '../openvpn_service.dart';
import 'package:flutter/services.dart';

class ProjectListScreen extends StatefulWidget {
  const ProjectListScreen({super.key});

  @override
  ProjectListScreenState createState() => ProjectListScreenState();
}

class ProjectListScreenState extends State<ProjectListScreen> {
  Future<void>? _initialFetchFuture;
  DateTime? lastBackPressTime;
  final OpenVPNService vpnService = OpenVPNService();

  @override
  void initState() {
    super.initState();
    _applyUserFilter();
  }

  Future<void> _applyUserFilter() async {
    final prefs = await SharedPreferences.getInstance();
    final username = prefs.getString('username') ?? '';
    final provider = Provider.of<ProjectProvider>(context, listen: false);
    const Map<String, String> userMapping = {
      'zhangjiakai': '章佳凯',
      'wangzizhu': '王子柱',
      'gaoyuancheng': '高垣成',
      'liujianlong': '刘建龙',
      'liuzhen': '刘真',
      'yupeizhong': '喻培忠',
      'chenzifeng': '陈梓峰',
      'zhaozong': '赵总',
      'jinzong': '金总',
      'liuchunlong': '刘春龙',
    };

    if (username.toLowerCase() == 'liuchunlong') {
      provider.filterProjects();
    } else {
      final String? chineseName = userMapping[username.toLowerCase()];
      if (chineseName != null) {
        provider.filterProjects(owner: chineseName);
      } else {
        provider.filterProjects(owner: '未知用户');
      }
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final provider = Provider.of<ProjectProvider>(context, listen: false);
    if (provider.isConnected && _initialFetchFuture == null) {
      _initialFetchFuture = provider.fetchProjects().then((_) {
        _applyUserFilter();
      });
    }
  }

  void _showProjectDetailDialog(BuildContext context, Project project) {
    if (!mounted) return;
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('项目 ${project.sequence}'),
        contentPadding: const EdgeInsets.all(24.0),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('产品分类: ${project.productCategory}'),
              Text('样品批量: ${project.sampleBatch}'),
              Text('软件状态: ${project.softwareStatus}'),
              Text('业务负责人: ${project.businessManager}'),
              Text('测试时间: ${project.testTime} 小时'),
              Text('预计时间: ${project.estimatedTime} 小时'),
              Text('开始时间: ${project.startTime ?? '未设置'}'),
              Text('完成时间: ${project.completionTime ?? '未设置'}'),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<ProjectProvider>(context);

    return PopScope(
      canPop: false, // 禁用默认返回
      onPopInvoked: (didPop) async {
        if (didPop) return; // 已处理返回则跳过
        final now = DateTime.now();
        if (lastBackPressTime == null ||
            now.difference(lastBackPressTime!) > const Duration(seconds: 2)) {
          lastBackPressTime = now;
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('再按一次退出应用')));
          return;
        }
        try {
          await vpnService.disconnect();
        } catch (e) {
          // 忽略断开错误，确保退出
        }
        SystemNavigator.pop();
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('项目列表'),
          actions: [
            IconButton(
              icon: Icon(
                provider.isConnected ? Icons.cloud_done : Icons.cloud_off,
                color: provider.isConnected ? Colors.green : Colors.grey,
              ),
              onPressed: () async {
                if (!mounted) return;
                try {
                  if (provider.isConnected) {
                    await provider.disconnect();
                    final prefs = await SharedPreferences.getInstance();
                    await prefs.setBool('autoLogin', false); // 取消自动登录
                    if (!mounted) return;
                    setState(() {
                      _initialFetchFuture = null;
                    });
                    if (mounted) {
                      ScaffoldMessenger.of(
                        context,
                      ).showSnackBar(const SnackBar(content: Text('已登出')));
                      Navigator.pushReplacementNamed(context, '/login');
                    }
                  } else {
                    if (mounted) {
                      Navigator.pushReplacementNamed(context, '/login');
                    }
                  }
                } catch (e) {
                  if (mounted) {
                    ScaffoldMessenger.of(
                      context,
                    ).showSnackBar(SnackBar(content: Text('登出失败: $e')));
                  }
                }
              },
            ),
          ],
        ),
        body: provider.isConnected
            ? FutureBuilder(
                future: _initialFetchFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return const Center(child: CircularProgressIndicator());
                  }
                  if (snapshot.hasError) {
                    return Center(child: Text('加载项目失败: ${snapshot.error}'));
                  }
                  if (provider.projects.isEmpty) {
                    return const Center(child: Text('暂无项目'));
                  }
                  return RefreshIndicator(
                    onRefresh: () async {
                      await provider.fetchProjects();
                      await _applyUserFilter();
                    },
                    child: ListView.builder(
                      itemCount: provider.projects.length,
                      itemBuilder: (context, index) {
                        final project = provider.projects[index];
                        return Card(
                          child: ListTile(
                            title: Text('项目 ${project.sequence}'),
                            subtitle: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text('产品分类: ${project.productCategory}'),
                                Text('软件状态: ${project.softwareStatus}'),
                                Text('业务负责人: ${project.businessManager}'),
                                Text('开始时间: ${project.startTime ?? '未设置'}'),
                                Text(
                                  '完成时间: ${project.completionTime ?? '未设置'}',
                                ),
                              ],
                            ),
                            onTap: () =>
                                _showProjectDetailDialog(context, project),
                          ),
                        );
                      },
                    ),
                  );
                },
              )
            : const Center(child: Text('请先登录')),
      ),
    );
  }
}
